package com.allwees.bs.core.model.user.context;

import com.allwees.bs.core.modelbase.constant.ResultEnum;
import com.allwees.bs.core.modelbase.exception.BusinessException;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

import java.util.Collection;

/**
 * @author yangylsky
 * @since 2019-08-30
 */
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public class CurrentUser extends User {

    private static final long serialVersionUID = 8980781356235774616L;

    private String userUuid;

    private String tokenUuid;

    private long expiredAt;

    public CurrentUser(String userUuid, String username, String pwd,Collection<? extends GrantedAuthority> authorities) {
        super(username, pwd, authorities);
        this.userUuid = userUuid;
    }

    public static CurrentUser getUser() {
        return getUser(true);
    }

    public static CurrentUser getUser(boolean throwsExceptionIfNotPresent) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !(auth.getPrincipal() instanceof CurrentUser)) {
            if (throwsExceptionIfNotPresent) {
                throw BusinessException.getInstance(ResultEnum.UNAUTHORIZED);
            }
            return null;
        }
        return (CurrentUser) auth.getPrincipal();
    }
}
